package run_cmd;

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(   run_cmd 
					get_results_run_cmd
					run_queue_cmd
					run_queue_parallel);



use strict;
use warnings;
use Carp;



# parameters 0 = cmd
#            1 = verbose
sub run_cmd
{
	my ($cmd_str, $verbose) = @_;
	#remove beginning white space and new lines
	$cmd_str =~tr/\t\n/ /d;
	$cmd_str =~ s/\s+/ /gm;
	if ($verbose)
	{
		carp $cmd_str;
	}
	system $cmd_str and croak "Failed [ $cmd_str ]\n$!\n";
}

sub get_results_run_cmd
{
	#remove beginning white space and new lines
	my $cmd = $_[0];
	$cmd =~tr/\t\n/ /d;
	$cmd =~ s/\s+/ /gm;
	if ($_[1])
	{
		carp $cmd;
	}
	open FROMEXEC, '-|' or exec $cmd or croak "Failed [ $cmd ]\n$!\n";
	my @lines = <FROMEXEC>;
	close FROMEXEC;
	return @lines;
}



sub get_queue_preamble($$$)
{
	my ($job_name, $queue_name, $priority) = @_;
	if ($job_name)
	{
		$job_name = " -N \"$job_name\"";
	}
	else
	{
		$job_name = " ";
	}
	$queue_name ||= "short_jobs.q";
	unless (defined $priority)
	{
		$priority = 20;
	}
	return "qrsh -now n -cwd -q $queue_name -p -$priority $job_name ";
}


sub run_queue_cmd
{
	my ($cmd_str, $job_name, $queue_name, $priority, $verbose) = @_;
	my $queue_preamble = get_queue_preamble($job_name, $queue_name, $priority);
	
	#remove beginning white space and new lines
	$cmd_str =~tr/\t\n/ /d;
	$cmd_str =~ s/\s+/ /gm;

	my $queue_cmd_str = $queue_preamble . '"' . $cmd_str . '"';
	if ($verbose)
	{
		carp $queue_cmd_str;
	}
	system $queue_cmd_str and croak "Failed [ $queue_cmd_str ]\n$!\n";
}


sub run_queue_parallel
{
	my ($cmds, $queue_name, $priority, $verbose) = @_;

	
	use Cwd;
	my $present_dir = getcwd();
	carp "Current directory = $present_dir\n" if $verbose;

	##DEBUGG
	#print STDERR "cwd = " . $present_dir . "\n";

	my @run_file_handles;
	
	for my $pair (@$cmds)
	{
		my ($cmd_str, $job_name, $working_dir, $description) = @$pair;
		##DEBUGG
		#print STDERR "params = \n" . join("\n", $cmd_str, $job_name, $working_dir, $description, "");

		my $queue_preamble = get_queue_preamble($job_name, $queue_name, $priority);
		
		# print description
		print $description if $description;

		# change directory
		chdir($working_dir) or croak ("Error:\n\tCould not change to [$working_dir]\n");
		
		#
		# Construct shell command
		# 	remove beginning white space and new lines
		# 
		$cmd_str =~tr/\t\n/ /d;
		$cmd_str =~ s/\s+/ /gm;
		my $queue_cmd_str = $queue_preamble . '"' . $cmd_str . '" |';
		carp $queue_cmd_str if ($verbose);
		print "$queue_cmd_str\n";

		my $run_fh;
		open($run_fh, $queue_cmd_str);
		push(@run_file_handles, $run_fh);

		chdir($present_dir) or croak ("Error:\n\tCould not change back to [$present_dir]\n");
	}

	# return to original directory
	chdir($present_dir) or croak ("Error:\n\tCould not change back to [$present_dir]\n");

	for my $run(@run_file_handles)
	{
		my $run_local = $run;
		while (<$run_local>)
		{
			sleep (1);
			print STDERR "here\n";
		}
	}
}


return 1;
